<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>bind实现漂亮的随机色</title>
    <style>
        *{
            padding: 0;
            margin: 0;
        }

        body{
            width: 100vw;
            height: 100vh;
            display: flex;
            justify-content: center;
            align-items: center;
        }

        h1{
            padding: 40px;
        }
    </style>
</head>
<body>
    <h1>xiasnn</h1>
    <script>
        function Color(element){
            this.element = element;
            this.color = ['red','orange','yellow','green','blue','purple'];
            this.show = () => {
                setInterval(function() {
                    // 这边的this指向的是windows，这边用bind改变this指向
                    let i = Math.floor(Math.random() * this.color.length);
                    this.element.style.backgroundColor = this.color[i];
                }.bind(this), 1000);
            }
        }

        let a = new Color(document.querySelector('body'));
        a.show();

        let b = new Color(document.querySelector('h1'));
        b.show();
    </script>
</body>
</html>